﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Ec_System.API
{
   public static class SerializeHelper
    {
        public static string Serialize<T>(T instance)
        {
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            //Add an empty namespace and empty value
            ns.Add("", "");

            XmlWriterSettings settings = new XmlWriterSettings();
            // Remove the <?xml version="1.0" encoding="utf-8"?>
            settings.OmitXmlDeclaration = true;
            // settings.DoNotEscapeUriAttributes = false;
            settings.Indent = true;
            settings.Encoding = Encoding.UTF8;
            settings.NewLineOnAttributes = true;
            XmlWriter sr = null;
            try
            {
                XmlSerializer xr = new XmlSerializer(typeof(T));
                StringBuilder sb = new StringBuilder();

                sr = XmlWriter.Create(sb, settings);
                xr.Serialize(sr, instance, ns);

                return (sb.ToString());
            }
            catch (Exception ex)
            {
                //Logger.Log(String.Format("Serialization Fail. Error Message : {0} {1}{2}", ex.Message, Environment.NewLine, ex.StackTrace));
                return null;
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }
        }

        /// <summary>
        /// XMLs to entity.
        /// </summary>
        /// <typeparam name="T">Xml對應的Entity type</typeparam>
        /// <param name="xml">The XML.</param>
        /// <returns>Xml對應的Entity</returns>
        public static T Deserialize<T>(string xml) where T : class
        {
            if (string.IsNullOrEmpty(xml))
            {
                return null;
            }
            else
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                byte[] byteArray = Encoding.UTF8.GetBytes(xml);
                MemoryStream stream = new MemoryStream(byteArray);

                return serializer.Deserialize(stream) as T;
            }
        }
    }
}
